package com.leyou.item.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.leyou.item.dto.SpecGroupDTO;
import com.leyou.item.dto.SpecParamDTO;
import com.leyou.item.entity.SpecGroup;
import com.leyou.item.mapper.SpecGroupMapper;
import com.leyou.item.service.SpecGroupService;
import com.leyou.item.service.SpecParamService;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class SpecGroupImpl extends ServiceImpl<SpecGroupMapper, SpecGroup> implements SpecGroupService {

    private final SpecParamService specParamService;

    public SpecGroupImpl(SpecParamService specParamService) {
        this.specParamService = specParamService;
    }

    @Override
    public List<SpecGroupDTO> querySpecList(Long cid) {

        //根据分类id查询对应的规格参数组集合，同时转换为DTO
        List<SpecGroupDTO> specGroupDTOS = SpecGroupDTO.convertEntityList(query().eq("category_id", cid).list());


        //根据分类查询当前分类下所有的规格参数
        List<SpecParamDTO> specParamDTOS = SpecParamDTO.convertEntityList(
                this.specParamService.query().eq("category_id", cid).list());

        // 对规格参数分组，groupId一致的在一组,map的key就是 groupBy的条件，groupId,value 就是当前可对应的分组集合 List<SpecParamDTO>
        Map<Long, List<SpecParamDTO>> map = specParamDTOS
                .stream()
                .collect(
                        Collectors.groupingBy(SpecParamDTO::getGroupId));

        //循环group分组，把查询转换后的规格参数赋值给对应的分组
        for (SpecGroupDTO specGroupDTO : specGroupDTOS) {
            specGroupDTO.setParams(map.get(specGroupDTO.getId()));
        }


        return specGroupDTOS;
    }
}
